﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using SystemHYS.API.Application.command.GualitySchemeCommmand;
using SystemHYS.Domian;
using SystemHYS.Infrstructre;
using SystemHYS.Infrstructre.Imp;
using SystemHYS.Infrstructre.Interface;
namespace SystemHYS.API.Application.commandler.GualitySchemeCommandler
{
    public class GualitySchemeCreateCommmandler:IRequestHandler<GualitySchemeCreateCommmand,int>
    {
        IGualitySchemeRepository Repository;
        IProjectSchemeRepository projectSchemeRepository;
        public SystemCoretext db;
        public GualitySchemeCreateCommmandler(IGualitySchemeRepository Repository, IProjectSchemeRepository projectSchemeRepository, SystemCoretext db)
        {
            this.Repository = Repository;
            this.projectSchemeRepository = projectSchemeRepository;
            this.db = db;
        }
 
        public async Task<int> Handle(GualitySchemeCreateCommmand request, CancellationToken cancellationToken)
        {
            using (var tran=await db.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable))
            {
                try
                {
                    var list = new GualityScheme()
                    {
                        gualitySchemeId = 0,
                        gualitySchemeNumbering = request.gualitySchemeNumbering,
                        gualitySchemeName = request.gualitySchemeName,
                        gualitySchemeState = request.gualitySchemeState,
                        gualityGroupId = request.gualityGroupId,
                        AddName = "李明",
                        AddTime = DateTime.Now.ToUniversalTime(),
                    };
                    await Repository.AddAsyn(list);
                    var id = list.gualitySchemeId;
                    foreach (var item in request.GualityProjectList)
                    {
                        await projectSchemeRepository.AddAsyn(new ProjectScheme()
                        {
                            gualityProjectId = item,
                            gualitySchemeId = id,
                            AddName = "李明",
                            AddTime = DateTime.Now.ToUniversalTime(),
                        });
                    }
                    await tran.CommitAsync();
                    return 1;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw;
                }
            }
            
        }
    }
}
